package com.mccken.practice.top100;

import java.util.LinkedList;
import java.util.Queue;

import cn.hutool.core.util.StrUtil;

/**
 * Definition for a binary tree node.
 *
 * @program: mccken-collect
 * @description:
 * @author: mccken
 * @create: 2024-03-04 23:16
 **/
public class TreeNodeUtil {

	// 前序遍历，构建TreeNode
	public static TreeNode buildTreeNode(String str) {
		// 将字符串转换为整数列表，null转换为特定值，比如Integer.MIN_VALUE  
		Queue<Integer> preorder = new LinkedList<>();
		for (String s : str.split(",")) {
			if ("null".equals(s)) {
//				preorder.add(Integer.MIN_VALUE);
				preorder.add(null);
			} else {
				preorder.add(Integer.parseInt(s));
			}
		}

		TreeNode root = new TreeNode(preorder.poll());
		Queue<TreeNode> treeNodeQueue = new LinkedList<>();
		treeNodeQueue.offer(root);

		while (!preorder.isEmpty() && !treeNodeQueue.isEmpty()) {
			TreeNode node = treeNodeQueue.poll();
			if (!preorder.isEmpty()) {
				Integer val = preorder.poll();
				if (val != null) {
					node.left = new TreeNode(val);
					treeNodeQueue.offer(node.left);
				}
			}

			if (!preorder.isEmpty()) {
				Integer val = preorder.poll();
				if (val != null) {
//				if (val != Integer.MIN_VALUE) {
					node.right = new TreeNode(val);
					treeNodeQueue.offer(node.right);
				}
			}
		}
		return root;

	}

	public static void main(String[] args) {
		String str = "1,2,3,null,4,null,5";
		TreeNode root = buildTreeNode(str);
		// 这里可以添加代码来遍历和验证构建的二叉树
		printTreeNode(root);
		System.out.println();
	}

	public static void printTreeNode(TreeNode root) {
		if (root == null) {
			return;
		}

		Queue<TreeNode> queue = new LinkedList<>(); // 创建一个队列用于层次遍历  
		queue.offer(root); // 将根节点入队  

		StringBuilder sb = new StringBuilder();
		while (!queue.isEmpty()) {
			TreeNode currentNode = queue.poll(); // 出队并访问当前节点  
			if (currentNode != null) {
				sb.append(currentNode.val).append(",");
				if (currentNode.left == null && currentNode.right == null) {
					continue;
				}
				queue.offer(currentNode.left); // 左子节点入队
				queue.offer(currentNode.right);
			} else {
				sb.append("null,");
			}

		}
		String str = sb.toString();
		System.out.println(StrUtil.removeSuffix(str, ","));
	}
}